package com.ssm.basis.service.config.middleware;

import org.springframework.boot.autoconfigure.cache.CacheManagerCustomizer;
import org.springframework.boot.autoconfigure.cache.RedisCacheManagerBuilderCustomizer;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;

import java.time.Duration;

import static com.ssm.basis.service.constant.CacheNameConstant.*;

@Configuration(proxyBeanMethods = false)
class CacheConfig {
    /**
     * @see ConcurrentMapCacheManager
     * SpringBoot 默认使用 SimpleCacheConfiguration，即使用 ConcurrentMapCacheManager 来实现缓存
     */
    // @Bean
    CacheManagerCustomizer<ConcurrentMapCacheManager> cacheManagerCustomizer() {
        // 内容为 null 值也缓存
        return cacheManager -> cacheManager.setAllowNullValues(false);
    }

    @Bean
    RedisCacheManagerBuilderCustomizer redisCacheManagerBuilderCustomizer() {
        // 设置过期时间
        return (builder) -> builder
                .withCacheConfiguration(DICT_TRANSLATE, RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofSeconds(10)))
                .withCacheConfiguration(MENUS_LIST, RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(1)))
                .withCacheConfiguration(MENUS_TREE, RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(1)));
    }
}
